package com.buluo.web.controller

import com.m1905hd.common.global.JSONCode
import com.m1905hd.common.util.DateUtils
import com.m1905hd.common.util.Page
import com.buluo.service.FilmService
import com.buluo.utils.ExeclView
import com.mongodb.BasicDBObject
import com.mongodb.DBObject
import org.apache.poi.hssf.usermodel.HSSFCell
import org.apache.poi.hssf.usermodel.HSSFRow
import org.apache.poi.hssf.usermodel.HSSFSheet
import org.apache.poi.hssf.usermodel.HSSFWorkbook
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.ui.ModelMap
import org.springframework.util.StringUtils
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.servlet.ModelAndView

import javax.servlet.http.HttpServletRequest

/**
 * Created by sunhao on 2016/12/16.
 */
@Controller
@RequestMapping(value = "film")
class FilmController {
    @Autowired
    FilmService filmService

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    def showList(Model model) {
//        model.addAttribute("climeTypes", this.filmService.listClime())
//        model.addAttribute("filmTypes", this.filmService.listFilmTypes())
//        model.addAttribute("channels", this.hdThirdChannelService.getAll())
        return "film/list"
    }

    @RequestMapping(value = "/list.json")
    def list(
            @RequestParam(defaultValue = "15") int limit,
            @RequestParam(defaultValue = "0") int pageIndex,
            @RequestParam(defaultValue = "0") int _id,
            @RequestParam(defaultValue = "-2") int status,
            @RequestParam(defaultValue = "-1") int vip,
            @RequestParam(defaultValue = "-1") int ft,
            String title, String rightEnd, String clime, String sort, String turnoff, String hdType, String mark,
            @RequestParam(defaultValue = "-1") int isonly) {
        pageIndex = pageIndex + 1

        def query = new BasicDBObject()
        if (_id != 0) {
            query.append("_id", _id)
        } else {
            if (!StringUtils.isEmpty(title)) {
                query.append("title", ~/${title}/)
            }
            if (status != -2) {
                query.append("status", status)
            }
            if (!StringUtils.isEmpty(rightEnd)) {
                if (2 == vip) {
                    query.append('bmonth', 1)
                } else {
                    query.append("vip", 1)
                }
                query.append("end", ['$lte': DateUtils.parseDate(rightEnd).getTime()] as BasicDBObject)
            }
            if (vip != -1 && !query.containsKey("vip")) {
                if (2 == vip) {
                    query.append('bmonth', 1)
                } else {
                    query.append("vip", vip)
                }

            }
            if (ft != -1) {
                if (0 == ft) {
                    query.append('filmid', ['$gt': 0] as BasicDBObject)
                } else {
                    query.append('filmid', ['$lt': 0] as BasicDBObject)
                }
            }
            if (!StringUtils.isEmpty(clime)) {
                query.append("clime", clime)
            }
            if (isonly != -1) {
                query.append("isonly", isonly)
            }
            if (!StringUtils.isEmpty(hdType)) {
                query.append("filmTypes", ['$all': [hdType]] as BasicDBObject)
            }
            if (!StringUtils.isEmpty(turnoff)) {
                if (turnoff.equals("on")) {
                    query.append("turnoff", turnoff)
                } else {
                    query.append("turnoff", ['$ne': "on"] as BasicDBObject)
                }

            }
        }
        def sortBasicDBObject = null
        if (!StringUtils.isEmpty(sort)) {
            sortBasicDBObject = new BasicDBObject(sort, -1)
        }
        if (!StringUtils.isEmpty(mark)) {
            Page page = this.hdThirdFilmsService.list(query, sortBasicDBObject, null, pageIndex, limit, mark)
            [results: page.count, rows: page.data]
        } else {
            Page page = this.filmService.list(query, sortBasicDBObject, null, pageIndex, limit)
            [results: page.count, rows: page.data]
        }
    }


    @RequestMapping(value = "/execl")
    def execl(
            @RequestParam(defaultValue = "15") int limit,
            @RequestParam(defaultValue = "0") int pageIndex,
            @RequestParam(defaultValue = "0") int _id,
            @RequestParam(defaultValue = "-2") int status,
            @RequestParam(defaultValue = "-1") int vip,
            @RequestParam(defaultValue = "-1") int ft,
            @RequestParam(defaultValue = "-1") int isonly,
            String title, String rightEnd, String clime, String sort, String hdType, String turnoff, String mark, ModelMap model) {
        pageIndex = pageIndex + 1

        def query = new BasicDBObject()
        if (_id != 0) {
            query.append("_id", _id)
        } else {
            if (!StringUtils.isEmpty(title)) {
                query.append("title", ~/${title}/)
            }
            if (status != -2) {
                query.append("status", status)
            }
            if (!StringUtils.isEmpty(rightEnd)) {
                if (vip == 2) {
                    query.append('bmonth', 1)
                } else {
                    query.append("vip", 1)
                }
                query.append("end", ['$lte': DateUtils.parseDate(rightEnd).getTime()] as BasicDBObject)
            }
            if (vip != -1 && !query.containsKey("vip")) {
                if (vip == 2) {
                    query.append('bmonth', 1)
                } else {
                    query.append("vip", vip)
                }
            }
            if (isonly != -1) {
                query.append("isonly", isonly)
            }
            if (ft != -1) {
                if (0 == ft) {
                    query.append('filmid', ['$gt': 0] as BasicDBObject)
                } else {
                    query.append('filmid', ['$lt': 0] as BasicDBObject)
                }
            }
            if (!StringUtils.isEmpty(clime)) {
                query.append("clime", clime)
            }
            if (!StringUtils.isEmpty(hdType)) {
                query.append("filmTypes", ['$all': [hdType]] as BasicDBObject)
            }
            if (!StringUtils.isEmpty(turnoff)) {
                if (turnoff.equals("on")) {
                    query.append("turnoff", turnoff)
                } else {
                    query.append("turnoff", ['$ne': "on"] as BasicDBObject)
                }

            }
        }
        def sortBasicDBObject = null
        if (!StringUtils.isEmpty(sort)) {
            sortBasicDBObject = new BasicDBObject(sort, -1)
        }
        List list
        DBObject object = [_id: 1, title: 1, director: 1, actor: 1, years: 1, bmonth: 1, iparea: 1, vip: 1, clime: 1, filmTypes: 1, status: 1, isonly: 1, redroadcast: 1, begin: 1, end: 1, created: 1, _created: 1] as BasicDBObject
        if (!StringUtils.isEmpty(mark)) {
            list = this.hdThirdFilmsService.getAll(query, sortBasicDBObject, object, mark)
        } else {
            list = this.filmService.getAll(query, sortBasicDBObject, object)
        }
        model.put("workbook", parseWorkBook(list, [_id: "id", title: "片名", director: "导演", actor: "演员", years: "年份", bmonth: "点播类型", iparea: "授权地", vip: "vip", clime: "地域", filmTypes: "类型", isonly: "合作", redroadcast: "转播", status: "状态", begin: "版权开始", end: "版权结束", created: "入库时间", _created: "电影网入库时间"]))
        return new ModelAndView(new ExeclView())

    }

    def HSSFWorkbook parseWorkBook(List dataList, Map keys) {
        HSSFWorkbook workbook = new HSSFWorkbook();//相当于JXL中的  WritableWorkbook
        HSSFSheet sheet = workbook.createSheet();


        HSSFRow row = sheet.createRow(0)
        keys.eachWithIndex { Map.Entry<Object, Object> entry, int i ->
            HSSFCell cell = row.createCell(i)
            cell.setCellType(HSSFCell.CELL_TYPE_STRING)
            cell.setCellValue(entry.value);
        }


        dataList.eachWithIndex { Object entry, int i ->
            row = sheet.createRow(i + 1)

            keys.eachWithIndex { Map.Entry<Object, Object> entry1, int index ->
                HSSFCell cell = row.createCell(index)
                cell.setCellType(HSSFCell.CELL_TYPE_STRING)
                def value = entry.get(entry1.key)
                if (value == null) {
                    value = ""
                }
                if (null != value && !"".equals(value)) {
                    if ("begin".equals(entry1.key) || "end".equals(entry1.key) || "created".equals(entry1.key) || "_created".equals(entry1.key)) {
                        value = DateUtils.formatDate(new Date(value as long))
                    }
                }
                cell.setCellValue(value.toString());
            }
        }


        return workbook
    }

    @RequestMapping(value = "edit.json")
    def edit(int _id, String title, String img, String description, String summary,
             double price, int weight, HttpServletRequest request,
             double score, String actor, String director, String clime,
             String years, String tag, int playTimes, int vip) {
        List<String> filmTypes = request.getParameterValues("filmTypes[]")

        def types = this.filmService.listFilmTypes()
        def hdTypeList = new ArrayList()
        filmTypes.each {
            if (!StringUtils.isEmpty(it) && types.contains(it)) {
                hdTypeList.add(it)
            }
        }
        def tags = tag.split(",|，")
        def obj = [img  : img, description: description, summary: summary, title: title,
                   price: price, weight: weight as int, filmTypes: hdTypeList, playTimes: playTimes as int,
                   score: score, actor: actor, director: director, clime: clime, years: years as int, tag: tags, vip: vip] as BasicDBObject
        this.filmService.update(_id, obj)
        return [code: JSONCode.SUCCESS.code]
    }

    @RequestMapping(value = "changeStatus/{id}.json")
    def changeStatus(@PathVariable("id") int id, int status) {
        if (status == -1) {
            return [code: JSONCode.ERROR.code]
        }
        int newStatus = status == 1 ? 0 : 1
        this.filmService.update(id, [status: newStatus] as BasicDBObject)
        return [code: JSONCode.SUCCESS.code]
    }
}
